package com.doge.calcalbum.business.trash

import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.db.model.Entry
import com.doge.calcalbum.utils.*

class TrashRepository {
    val entryList = db.entryDao().queryDeletedLiveData()

    fun recover(entries: List<Entry>) = runInTransaction {
        entries.map { it.copy(albumId = recoverAlbumId(it), deleteTime = 0) }
            .forEach(db.entryDao()::update)
        db.albumDao().updateCount(Album.DEFAULT_VIDEO_ID)
        db.albumDao().updateCount(Album.DEFAULT_PICTURE_ID)
    }

    fun delete(entries: List<Entry>) = runInTransaction {
        entries.forEach(db.entryDao()::delete)
        runOnIO { entries.forEach(Entry::deleteFile) }
    }

    fun clearExpired() = runInTransaction {
        val expiredTimestamp: Long = System.currentTimeMillis() - TRASH_CLEAR_DELAY_TIME
        val trashEntryList: List<Entry> = db.entryDao().queryDeleted().filter {
            it.deleteTime in 1 until expiredTimestamp
        }
        log("clearExpired size ${trashEntryList.size}")
        trashEntryList.forEach(db.entryDao()::delete)
        runOnIO { trashEntryList.forEach(Entry::deleteFile) }
    }

    private fun recoverAlbumId(entry: Entry): Int {
        return if (entry.isVideoSource) Album.DEFAULT_VIDEO_ID else Album.DEFAULT_PICTURE_ID
    }
}